const fs = require('fs')
const path = require('path')

//
// 创建存储用户信息的文件夹，如果不存在的话
exports.createUserInfoFolder = function (account) {
  const appRoot = path.dirname(require.main.filename)
  const userFolderPath = path.join(appRoot, `../AllUser/${account}`)

  if (!fs.existsSync(userFolderPath)) {
    fs.mkdirSync(userFolderPath)
    console.log('User folder created successfully')
  } else console.log(`User: ${account} folder already exists`)
}

//
// 设置聊天记录
exports.setChatRecord = (account, chatRecord, receiverId) => {
  const appRoot = path.dirname(require.main.filename)
  const p = path.join(appRoot, `../AllUser/${account}/chatRecord.json`)

  // 如果文件不存在，则创建新文件
  if (!fs.existsSync(p)) fs.writeFileSync(p, '{}')

  // 读取已有数据
  let jsonData = JSON.parse(fs.readFileSync(p).toString())
  let receiverChatList = jsonData[receiverId]

  if (!receiverChatList) receiverChatList = [chatRecord]
  else receiverChatList.push(chatRecord)

  jsonData[receiverId] = receiverChatList

  // 写入数据
  fs.writeFileSync(p, JSON.stringify(jsonData, null, 2), { flag: 'w' })
  console.log('Data appended to file successfully')
}

//
// 获取聊天记录
exports.getChatRecord = (account, receiverId) => {
  const appRoot = path.dirname(require.main.filename)
  const p = path.join(appRoot, `../AllUser/${account}/chatRecord.json`)

  if (!fs.existsSync(p)) return {}

  // 读取已有数据
  let jsonData = JSON.parse(fs.readFileSync(p).toString())

  let receiverChatList = jsonData[receiverId]
  if (!receiverChatList) receiverChatList = []

  return receiverChatList
}
